package com.zh.mediaservice.service.impl;


import com.zh.mediacommon.constant.JWTClaimsConstant;
import com.zh.mediacommon.constant.MessageConstant;
import com.zh.mediacommon.ecxeption.DoctorLoginException;
import com.zh.mediacommon.properties.JwtProperties;
import com.zh.mediacommon.util.JwtUtil;
import com.zh.mediapojo.dto.DoctorLoginDTO;
import com.zh.mediapojo.dto.DoctorUpdatePasswordDTO;
import com.zh.mediapojo.entity.DoctorLogin;
import com.zh.mediapojo.vo.DoctorLoginVO;
import com.zh.mediaservice.mapper.DoctorLoginMapper;
import com.zh.mediaservice.service.DoctorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class DoctorServiceImpl implements DoctorService {
    @Autowired
    private DoctorLoginMapper doctorLoginMapper;
    @Autowired
    private JwtProperties jwtProperties;
    @Override
    public DoctorLoginVO login(DoctorLoginDTO doctorLoginDTO) {
        DoctorLogin doctorLogin = doctorLoginMapper.login(doctorLoginDTO);
        if(doctorLogin==null)
            throw new DoctorLoginException(MessageConstant.NOT_FOUND_ACCOUNT);
        if(!doctorLogin.getPassword().equals(DigestUtils.md5DigestAsHex(doctorLoginDTO.getPassword().getBytes()).toUpperCase())){
            log.info("密码错误,密码:{}",DigestUtils.md5DigestAsHex(doctorLoginDTO.getPassword().getBytes()));
            throw new DoctorLoginException(MessageConstant.USER_PASSWORD_ERROR);
        }
        Map<String,Object>claims=new HashMap<>();
        claims.put(JWTClaimsConstant.USER_ID,doctorLogin.getDid());

        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(),jwtProperties.getTtl(),claims);
        return DoctorLoginVO.builder().token(token).did(doctorLogin.getDid()).isFirst(doctorLogin.getIsFirst()).build();
    }

    @Override
    public void updatePassword( DoctorUpdatePasswordDTO depositPasswordDTO) {
        doctorLoginMapper.updatePassword(depositPasswordDTO.getId(),DigestUtils.md5DigestAsHex(depositPasswordDTO.getPassword().getBytes()).toUpperCase());

    }
}
